package com.xiao.news.fragment;

import java.io.InputStream;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.bokeyuan.R;
import com.xiao.activity.MainActivity;
import com.xiao.bokeyuan.utils.HttpUtils;
import com.xiao.bokeyuan.utils.HttpUtils.Method;
import com.xiao.news.listview.NewsInfo;
import com.xiao.slipUtils.D;
import com.xiao.sqlite.SqlLabel;

public class FragmentNewsContent extends Fragment {

	private ProgressDialog mpb;

	SqlLabel mSql;
	TextView mTvTitle;
	WebView mWeb;
	ArrayList<NewsInfo> mListNews;
	NewsInfo info;
	//��ϰ������
	MainActivity mContext;
	//�����Ƿ���ʾlebel��ǩ
	View mLebel;
	//���۰�ť
	ImageView mImageComment;
	//�����ǩ��ť
	ImageView mImageSave;
	//�������
	ImageView moffline;
	FragmentManager mAnager;
	FragmentTransaction mFt;
	//��ȡ�������ݵĵ�ַ
	String murl;
	//�����Ž���õ�����������id
	String mId;
	//��ȡ�����������ӵ�ַ
	String mLink;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup layout,
			Bundle savedInstanceState) {
		//��ȡ������
		mContext = (MainActivity) getActivity();
		layout=(ViewGroup) inflater.inflate(R.layout.fragment_news_content, null);
		Bundle bundle=getArguments();
		//�������ݿ����
		mSql=new SqlLabel(mContext);
		String url=bundle.getString(D.NEWS_URL);
		murl=url;
		//�����Ž���õ�����������id
		mId=bundle.getString("id");
		//��ȡ�����������ӵ�ַ
		mLink=bundle.getString("link");
		initData(layout);
		pullParserNews(url);
		setLayoutListener(layout);
		return layout;
	}

	private void setLayoutListener(ViewGroup layout) {
		// TODO Auto-generated method stub
		mWeb.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				// TODO Auto-generated method stub


				new ShowLabel().execute();


				return true;
			}
		});
		//		mContext.mslideUtils.setTouchListener(mWeb);
	}

	private void initData(ViewGroup layout) {
		// TODO Auto-generated method stub
		mListNews=new ArrayList<NewsInfo>();
		mTvTitle=(TextView) layout.findViewById(R.id.f_n_title);
		mWeb=(WebView) layout.findViewById(R.id.f_n_web);
		mLebel = layout.findViewById(R.id.f_n_label);
		mImageComment=(ImageView) layout.findViewById(R.id.lebel_comment);
		mImageSave=(ImageView) layout.findViewById(R.id.lebel_save);
		moffline=(ImageView) layout.findViewById(R.id.lebel_lebel);
	}

	/**
	 * ���������ݽ�������
	 * @param url  ��������������ַ
	 */
	private void pullParserNews(String url) {
		// TODO Auto-generated method stub
		new DownLoadItemNews().execute(url);
	}

	/**
	 * 
	 * @author ��Чΰ
	 *
	 */
	class  DownLoadItemNews extends AsyncTask<String, Void, ArrayList<NewsInfo>>{



		@Override
		protected void onPreExecute() {
			if(mpb==null){
				mpb=ProgressDialog.show(mContext, "���ݼ�����", "loding...");
				//					mpb=new ProgressDialog(mContext);
				//					mpb.setTitle("����������");
				//					mpb.show();
			}else{
				mpb.show();
			}
		}

		@Override
		protected ArrayList<NewsInfo> doInBackground(String... params) {
			String url=params[0];
			InputStream in;
			try {
				in = HttpUtils.getInputStream(url, null, Method.GET, "utf-8");
				// ����pull������������
				XmlPullParserFactory factory = XmlPullParserFactory
						.newInstance();
				// ��������������
				XmlPullParser parser = factory.newPullParser();
				parser.setInput(in, "utf-8");
				for (int eventType = XmlPullParser.START_DOCUMENT;
						eventType != XmlPullParser.END_DOCUMENT; eventType = parser.next()) {
					if (eventType == XmlPullParser.START_TAG) {
						// ��ȡ��ǩ����
						String tagName = parser.getName();
						if(D.NewsContentItem.TITLE.equals(tagName)){
							info=new NewsInfo();
							info.setTitle(parser.nextText());
						}else if(D.NewsContentItem.CONTENT.equals(tagName)){
							info.setContent(parser.nextText());
							mListNews.add(info);
						}

					} else if (eventType == XmlPullParser.END_TAG) {

						String tagName = parser.getName();
						//						if(D.NewsContentItem.CONTENT.equals(tagName)){
						//							mListNews.add(info);
						//						}
					}
				}

				// //����listview ����
				// setAdapter();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return mListNews;
		}
		@Override
		protected void onPostExecute(ArrayList<NewsInfo> listinfo) {

			if(mpb!=null){
				mpb.setTitle("���ݼ������");
				mpb.dismiss();
			}
			// TODO Auto-generated method stub
			super.onPostExecute(listinfo);
			NewsInfo info=listinfo.get(0);
			//shezhi biao ti
			mTvTitle.setText(info.getTitle());

			WebSettings settings = mWeb.getSettings();
			settings.setDefaultTextEncodingName("utf-8");
			settings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
			String html=info.getContent();
			html="<Content>"+html+"</Content>";
			/* baseUrl:����Ŀ¼��������"file:///mnt/sdcard/��ָ��Ŀ¼������ָ���ļ���
			 data:��ʾ���ı���HTML��ʽ
			 mimeType:������Դ��ý�����ͣ�����ȡֵtext/html, image/jpeg��
			 encoding:�����ʽ
			 historyUrl:��ʷ��¼
			 loadDataWithBaseURL(baseUrl, data, mimeType,
			 encoding, historyUrl);*/
			mWeb.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);
		}
	}

	/**
	 * ���غ���ʾlebel �˵�
	 * @author ��Чΰ
	 *
	 */
	class ShowLabel extends AsyncTask<Void, Integer, Integer>{
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			//���ñ����ǩ��ť
			setSavaeListener();
			//�������۰�ť8
			setCommentListener();
			//�������������ǩ
			setOffineBrowse();
		}
		@Override
		protected Integer doInBackground(Void... params) {
			// TODO Auto-generated method stub
			publishProgress(1);
			SystemClock.sleep(2000);

			return 0;
		}
		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
			int v=values[0];
			if(v==1){
				mLebel.setVisibility(View.VISIBLE);
			}
			mAnager=getFragmentManager();
			mFt=mAnager.beginTransaction();

		}


		@Override
		protected void onPostExecute(Integer result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			mLebel.setVisibility(View.GONE);

			//			mLebel.set
		}

		/**
		 * �������
		 */
		private void setOffineBrowse() {
			moffline.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					SQLiteDatabase db = mSql.getWritableDatabase();
					//db.execSQL("insert into users(_id,name,password,phone,email)values(null,'"+name+"','"+pwd+"',"+phone+",'"+email+"')");
					//���������ʱ �򱣴浱ǰ����  �����������
					db.execSQL("insert into offline(_id,mid,title,summary,content)values(null,'"+mId+"','"+mListNews.get(0).getTitle()+"','"+null+"','"+mListNews.get(0).getContent()+"')");
					//�ر����ݿ�
					db.close();		
					Toast.makeText(mContext, "保存成功", 1000).show();
				}
			});

		}
	}
	/**
	 * 	//�������۰�ť
	 */
	private void setCommentListener() {
		mImageComment.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				//����fragment����
				Fragment f=new FragmentComment();
				Bundle p=new Bundle();
				//���������ݵĵ�ַ���ݸ�������Ƭ
				p.putString(D.NewsContentItem.ID, murl);
				p.putString(D.NewsContentItem.TITLE, mListNews.get(0).getTitle());
				f.setArguments(p);
				//��fragment�滻��
				mFt.replace(R.id.fl_details, f);
				mFt.addToBackStack(null);
				//				f..setmcon
				//				mContext.mfram.setVisibility(1);
				mFt.commit();

			}
		});
	}
	/**
	 * //���ñ����ǩ��ť
	 */
	private void setSavaeListener() {
		mImageSave.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				SQLiteDatabase db = mSql.getWritableDatabase();
				//db.execSQL("insert into users(_id,name,password,phone,email)values(null,'"+name+"','"+pwd+"',"+phone+",'"+email+"')");
				//���������ʱ �򱣴浱ǰ���ű�ǩ
				db.execSQL("insert into BookLabel(_id,mid,name,url)values(null,'"+mId+"','"+mListNews.get(0).getTitle()+"','"+mLink+"')");
				//�ر����ݿ�
				db.close();		
				Toast.makeText(mContext, "保存成功", 1000).show();
			}
		});
	}
}
